//
// Created by 19854 on 23/04/30.
//

//#include <freertos/task.h>
#include "BUZZERTask.h"

TaskHandle_t buzzerTaskHand;
TaskHandle_t buzzerRunHand = nullptr;

void buzzerRun(void *)
{
    while (true)
    {
        digitalWrite(BUZZER_PIN, LOW);
        vTaskDelay(500);
        digitalWrite(BUZZER_PIN, HIGH);
        vTaskDelay(500);
    }
}

void buzzerTask(void *ptParam)
{
    uint32_t notifyVal;

    pinMode(BUZZER_PIN, OUTPUT);
    digitalWrite(BUZZER_PIN,HIGH);
    uint32_t triggerTaskNum = 0;//当前触法报警任务的个数

    while (true)
    {
        notifyVal = ulTaskNotifyTake(pdTRUE, //pdTRUE 运行完后，清零
                                     portMAX_DELAY);
        Serial.print("收到通知:");
        Serial.println(notifyVal);

        if (notifyVal < 100)
        {
            triggerTaskNum++;
        } else
        {
            triggerTaskNum--;
        }
        if (triggerTaskNum)
        {
            if (buzzerRunHand == nullptr)
            {
                xTaskCreatePinnedToCore(buzzerRun, "buzzerRun", 1024, nullptr, 1, &buzzerRunHand, 1);
            }
        } else
        {
            if (buzzerRunHand != nullptr)
            {
                vTaskDelete(buzzerRunHand);
                buzzerRunHand= nullptr;
                digitalWrite(BUZZER_PIN,HIGH);
            }
        }

    }
}
